// JavaScript Document

function addToolMedicion()
{
  var marker1;
  var marker2;
  var label1;
  var label2;
  var button=0;
  var dist=0;
  var line;
  var poly;
  var medicionIcon = new GIcon();	        
  medicionIcon.iconSize = new GSize(24, 24);
  medicionIcon.iconAnchor = new GPoint(10, 24);
  medicionIcon.infoWindowAnchor = new GPoint(5, 1);
  
  map.getDragObject().setDraggableCursor('crosshair');

  function toolMedicion(){
    if(marker1&&marker2)
    line = [marker1.getPoint(),marker2.getPoint()];
    dist=marker1.getPoint().distanceFrom(marker2.getPoint());
    dist=dist.toFixed(0)+"m";
    if(parseInt(dist)>10000){dist=(parseInt(dist)/1000).toFixed(1)+"km";}
    label1.setContents(dist);label2.setContents(dist);
    label1.setPoint(marker1.getPoint());
    label1.setContents(dist);
    label2.setPoint(marker2.getPoint());
    if(poly)map.removeOverlay(poly);
    poly = new GPolyline(line,'#202020', 2, 0.9)
    map.addOverlay(poly);
  }

  /*if (mapEventsHandlers.containsKey('click')){
	  GEvent.removeListener(mapEventsHandlers.get('click'));
  }*/

  var toolMedicionClickListener = GEvent.addListener(map, 'click', function(overlay,pnt) 
  {
  if(pnt&&button==0)
  {
	medicionIcon.image = 'images/gmapTools/medicionIni.png';
    marker1 = new GMarker(pnt,{icon:medicionIcon, draggable: true});
    map.addOverlay(marker1);
    marker1.enableDragging();
    label1=new ELabel(pnt, dist,"GMapELabelStyle",new GSize(2,20),60);
    map.addOverlay(label1);
	medicionIcon.image = 'images/gmapTools/medicionFin.png';
    marker2 = new GMarker(pnt,{icon:medicionIcon, draggable: true});
    map.addOverlay(marker2);
    marker2.enableDragging();
    label2=new ELabel(pnt, dist,"GMapELabelStyle",new GSize(2,20),60);
    map.addOverlay(label2);
  }
  GEvent.addListener(marker1,"drag",function(){toolMedicion();});
  GEvent.addListener(marker1,"dblclick",function(){clrToolMedicion();});
  GEvent.addListener(marker2,"drag",function(){toolMedicion();});
  GEvent.addListener(marker2,"dblclick",function(){clrToolMedicion();});
  button++;
  //ahora remuevo el listener y dejo el que tenia antes el mapa
  GEvent.removeListener(toolMedicionClickListener);
  /*if (mapEventsFunctions.containsKey('click')){
	  var newOnClickMapListener = GEvent.addListener(map,"click",mapEventsFunctions.get('click'));
  	  mapEventsHandlers.put("click",newOnClickMapListener);
  }*/
  //vuelvo el cursor del mapa al que tenia antes
  map.getDragObject().setDraggableCursor(mapActiveCursor);	  
  });


  function clrToolMedicion(){
    map.removeOverlay(poly);
    map.removeOverlay(marker1);
    map.removeOverlay(marker2);
    map.removeOverlay(label1);
    map.removeOverlay(label2);
    button=0;
    dist=0;
    }
}